const passport = require('passport');
const GitHubStrategy = require('passport-github2').Strategy;

const User = require('../models/mongo-account');
const init = require('./init');

passport.use(new GitHubStrategy(
  {
    clientID: process.env.GITHUB_CLIENT_ID,
    clientSecret: process.env.GITHUB_CLIENT_SECRET,
    callbackURL: process.env.GITHUB_CLIENT_CALLBACK,
    scope: ['user:email'],
  },
  (accessToken, refreshToken, profile, done) => {
    const searchQuery = {
      name: profile.displayName,
    };

    const updates = {
      name: profile.displayName,
      someID: profile.id,
    };

    const options = {
      upsert: true,
    };

    // update the user if s/he exists or add a new user
    User.findOneAndUpdate(searchQuery, updates, options, (err, user) => {
      if (err) {
        return done(err);
      }
      return done(null, user);
    });
  },
));

// serialize user into the session
init();

module.exports = passport;
